package com.naizhuai.ui.management;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.naizhuai.MainActivity;
import com.naizhuai.Model.db.search.SearchHistoryBean;
import com.naizhuai.R;
import com.naizhuai.network.exception.ApiException;
import com.naizhuai.network.exception.ServerException;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.CircleImageView;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.ui.components.TipDialog;
import com.naizhuai.ui.entity.management.CompanyBean;
import com.naizhuai.ui.entity.management.DepartmentBean;
import com.naizhuai.ui.entity.management.PersonUserEditBean;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStore;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.ui.management.presenter.UserSearchDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.PersonRadarActivity;
import com.naizhuai.ui.user.UserManageDataApiStoreIml;
import com.naizhuai.util.AESCrypt;
import com.naizhuai.util.ActivityStackManager;
import com.naizhuai.util.ConstantsPersonResources;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.HideNumberUtils;
import com.naizhuai.util.ImageUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.NaizhuAILog;
import com.naizhuai.util.PermissionRequest;
import com.naizhuai.util.PhoneUtils;
import com.naizhuai.util.RxUtils;
import com.naizhuai.util.SharedPreferenceUtil;
import com.naizhuai.util.ToastCompat;
import com.naizhuai.util.UidUtil;

import java.security.GeneralSecurityException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscription;

/**
 * 公司个人详情列表
 */
public class CompanyUserDetailsMsgActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "CompanyUserDetailsMsgActivity";
    private static final int OPERATE_USER_CODE = 2000;

    @BindView(R.id.user_thumb)
    CircleImageView thumbImage;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.department_name)
    TextView departName;
    @BindView(R.id.company_power_msg)
    TextView companyPowerName;
    @BindView(R.id.department_power_msg)
    TextView departmentPowerName;
    @BindView(R.id.phone_number)
    TextView phoneNumber;
    @BindView(R.id.more_action_btn)
    ImageView editBtn;

    @BindView(R.id.department_power_layout)
    RelativeLayout departPowerLayout;

    private PersonUserBean actionUser;

    private CompanyManageDataApiStore apiStore;
    private int isSelf;
    private Subscription userinfoSub;
    private String userId;
    private int deleteType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apiStore = CompanyManageDataApiStoreIml.getInstance();
        initBasicData();
    }


    private void initBasicData() {
        Bundle intentBundle = getIntent().getExtras();
        if (intentBundle != null) {
            userId = intentBundle.getString(PersonUserBean.USER_ID_KEY);
            if (!TextUtils.isEmpty(userId)) {
                UserManageDataApiStoreIml.getInstance().searchUserInfo(userId)
                        .subscribe(observerRequestUserDetails);
            }
        }
    }

    private void requestUserData(String departId) {
        if (!RxUtils.isNetRunning(userinfoSub)) {
            userinfoSub = UserManageDataApiStoreIml.getInstance().getuserinfo().subscribe(new Observer<PersonUserBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    hideWaitDialog();
                    ApiException.showException(e, CompanyUserDetailsMsgActivity.this);
                }

                @Override
                public void onNext(PersonUserBean personUserBean) {
                    hideWaitDialog();
                    String userDepartmentId = personUserBean.getDepartmentId();
                    String userDepartmentCode = personUserBean.getDepartmentPowerCode();
                    String userCompanyCode = personUserBean.getCompanyPowerCode();
                    if (userCompanyCode.equals(ConstantsState.COM_TARGET_MANAGER_LEVEL) || (userDepartmentId.equals(departId) && userDepartmentCode.equals(ConstantsState.DEPARTMENT_MANAGER_POWER))) {
                        editBtn.setVisibility(View.VISIBLE);
                    } else {
                        editBtn.setVisibility(View.GONE);
                    }

                }
            });
            showWaitDiaLog(userinfoSub);
        }
    }


    private Observer<PersonUserBean> observerRequestUserDetails = new Observer<PersonUserBean>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
//            if (e instanceof ServerException) {
            if (e instanceof ApiException) {
                ApiException server = (ApiException) e;
                DialogUtils.showPromptDialog(CompanyUserDetailsMsgActivity.this, server.getDisplayMessage());
            }
            hideWaitDialog();
        }

        @Override
        public void onNext(PersonUserBean result) {
            hideWaitDialog();
            if (result != null) {
                actionUser = result;
                actionUser.setUid(userId);
                requestUserData(actionUser.getDepartmentId());
                initDataView();
            } else {
                DialogUtils.showPromptDialog(CompanyUserDetailsMsgActivity.this, getString(R.string.no_user));
            }
        }
    };

    private void initDataView() {
        if (getShareValue(PersonUserBean.USER_ID_KEY, "-1").equals(actionUser.getUid()))
            isSelf = ConstantsState.QUICK_BY_SELF;
        else
            isSelf = ConstantsState.QUICK_BY_OTHERS;
        ImageUtils.glideThumbViewByUrl(this, thumbImage, actionUser.getUserLogoUrl());
        phoneNumber.setText(HideNumberUtils.hidePhoneNumber(actionUser.getPhoneNumber()));
        if (TextUtils.isEmpty(actionUser.getDepartmentId())) {
            departName.setText(getString(R.string.not_in_department));
            departPowerLayout.setVisibility(View.GONE);
        } else
            departName.setText(actionUser.getDepartmentName());
        if (TextUtils.isEmpty(actionUser.getCompanyPowerMsg()))
            companyPowerName.setText(ConstantsState.COM_NORMAL_POWER_LEVEL_STRING);
        else
            companyPowerName.setText(actionUser.getCompanyPowerMsg());
        if (departPowerLayout.getVisibility() == View.VISIBLE) {
            if (TextUtils.isEmpty(actionUser.getDepartmentPowerMsg()))
                departmentPowerName.setText(ConstantsState.DEPARTMENT_NORMAL_POWER_STRING);
            else
                departmentPowerName.setText(actionUser.getDepartmentPowerMsg());
        }
        userName.setText(actionUser.getShowName());
    }


    private Observer<String> observerActionFromDepartment = new Observer<String>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            hideWaitDialog();
            NaizhuAILog.e("onError(Throwable e)=" + e.getMessage());
            ApiException.showException(e, getActivityContext(), true);
        }

        @Override
        public void onNext(String result) {
            NaizhuAILog.e("onNext(String result)=" + result);
            hideWaitDialog();
            if (!ConstantsState.isResultOk(result)) {
                shortToast(getResources().getString(R.string.action_fail));
            } else {
                shortToast(getResources().getString(R.string.action_ok));
                if (deleteType == ConstantsState.DELETE_FROM_COMPANY && isOperationSelf()) {
                    IntentUtils.startActivity(getActivityContext(), MainActivity.class);
                    MainActivity.updateUserData();
//                    ActivityStackManager.getInstance().killAllActivityExceptOne(MainActivity.class);
                } else
                    finish();
            }
        }
    };

    private boolean isOperationSelf() {
        return getShareValue(PersonUserBean.USER_ID_KEY, "").equals(userId);
    }

    private Observer<String> observerActionFromCompany = new Observer<String>() {
        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            if (e instanceof ApiException) {
                ApiException server = (ApiException) e;
                DialogUtils.showPromptDialog(CompanyUserDetailsMsgActivity.this, server.getDisplayMessage());
            }
        }

        @Override
        public void onNext(String result) {
            if (!ConstantsState.isResultOk(result)) {
                ToastCompat.showToast(CompanyUserDetailsMsgActivity.this, getResources().getText(R.string.action_fail), Toast.LENGTH_SHORT);
            } else {
                ToastCompat.showToast(CompanyUserDetailsMsgActivity.this, getResources().getText(R.string.action_ok).toString(), Toast.LENGTH_SHORT);
                if (isSelf == ConstantsState.QUICK_BY_SELF)
                    IntentUtils.startActivity(CompanyUserDetailsMsgActivity.this, MainActivity.class);
                else
                    IntentUtils.startActivity(CompanyUserDetailsMsgActivity.this, CompanyTotalStructureActivity.class);
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_company_user_details_layout;
    }

    @OnClick({R.id.base_back_icon, R.id.more_action_btn, R.id.user_grew})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_back_icon:
                super.onBackPressed();
                break;
            case R.id.more_action_btn:
                //进入用户操作界面
                PersonUserEditBean editBean = new PersonUserEditBean();
                editBean.setPersonBean(actionUser);
                editBean.setBeDepartPowerCode(actionUser.getDepartmentPowerCode());
                editBean.setBeDepartPowerMsg(actionUser.getDepartmentPowerMsg());
                editBean.setBeCompanyPowerCode(actionUser.getCompanyPowerCode());
                editBean.setBeCompanyPowerMsg(actionUser.getCompanyPowerMsg());
                IntentUtils.startActivityWithObjectForResult(PersonUserBean.USER_KEY, editBean, this, CompanyUseOperatActivity.class, OPERATE_USER_CODE);
                break;
            case R.id.user_grew:
                //进入雷达图界面
                IntentUtils.startActivityWithString(PersonUserBean.USER_ID_KEY, actionUser.getUid(), this, PersonRadarActivity.class);
                break;
//            case R.id.phone_call_action:
//                getPermissionRequest().request(new PermissionRequest.PermissionCallback() {
//                    @Override
//                    public void onSuccessful() {
//                        PhoneUtils.CallPhone(actionUser.getPhoneNumber(), CompanyUserDetailsMsgActivity.this);
//                    }
//
//                    @Override
//                    public void onFailure() {
//                        shortToast(getText(R.string.no_phone_permission).toString());
//                    }
//                }, new String[]{Manifest.permission.CALL_PHONE});
//                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        deleteType = -1;
        PersonUserEditBean userBean = (PersonUserEditBean) data.getSerializableExtra(PersonUserBean.USER_KEY);
        if (userBean == null)
            return;
        switch (resultCode) {
            case CompanyUseOperatActivity.RESULT_SAVE:
                //保存修改用户信息之后-》提交修改数据接口
                PersonUserBean personBean = userBean.getPersonBean();
                NaizhuAILog.e("Uid=" + personBean.getUid());
                NaizhuAILog.e("getDepartmentId=" + actionUser.getDepartmentId());
                NaizhuAILog.e("getAfDepartPowerCode=" + userBean.getAfDepartPowerCode());
                NaizhuAILog.e("getAfCompanyPowerCode=" + userBean.getAfCompanyPowerCode());

                if (userBean.hasChangeDepartmentPower())
                    apiStore.updateUserInfo(personBean.getUid(), actionUser.getDepartmentId(), userBean.getAfDepartPowerCode())
                            .subscribe(new Observer<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {
                                    if (e instanceof ApiException) {
                                        ApiException ae = (ApiException) e;
                                        DialogUtils.showPromptDialog(CompanyUserDetailsMsgActivity.this, ae.getDisplayMessage());
                                    } else
                                        NaizhuAILog.e(e.getLocalizedMessage());
                                }

                                @Override
                                public void onNext(String s) {
                                    if (ConstantsState.isResultOk(s)) {
                                        departmentPowerName.setText(userBean.getAfDepartPowerMsg());
                                        shortToast(getString(R.string.submit_ok));
                                    } else
                                        shortToast(getString(R.string.submit_fail));
                                }
                            });
                if (userBean.hasChangeCompanyPower())
                    apiStore.updateUserInfoFromCompany(personBean.getUid(), userBean.getAfCompanyPowerCode())
                            .subscribe(new Observer<String>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {
                                    if (e instanceof ApiException) {
                                        ApiException ae = (ApiException) e;
                                        DialogUtils.showPromptDialog(CompanyUserDetailsMsgActivity.this, ae.getDisplayMessage());
                                    } else
                                        NaizhuAILog.e(e.getLocalizedMessage());
                                }

                                @Override
                                public void onNext(String s) {
                                    if (ConstantsState.isResultOk(s)) {
//                                        companyPowerName.setText(userBean.getAfCompanyPowerMsg());
                                        UserManageDataApiStoreIml.getInstance().searchUserInfo(userId)
                                                .subscribe(observerRequestUserDetails);
                                        shortToast(getString(R.string.submit_ok));
                                    } else
                                        shortToast(getString(R.string.submit_fail));
                                }
                            });
                break;
            case CompanyUseOperatActivity.RESULT_DELETE_FROM_COMPANY:
                NaizhuAILog.e("UidUtil(actionUser.getUid())=" + new UidUtil(actionUser.getUid()).toString());
                NaizhuAILog.e("actionUser.getDepartmentId())=" + actionUser.getDepartmentId());
                deleteType = ConstantsState.DELETE_FROM_COMPANY;
                break;
            case CompanyUseOperatActivity.RESULT_DELETE_FROM_DEPARTMENT:
                NaizhuAILog.e("UidUtil(actionUser.getUid())=" + new UidUtil(actionUser.getUid()).toString());
                NaizhuAILog.e("actionUser.getDepartmentId())=" + actionUser.getDepartmentId());
                deleteType = ConstantsState.DELETE_FROM_DEPARTMENT;
                break;
        }
        if (deleteType != -1) {
            Subscription deleteSub = apiStore.deletePersonFromCompanyByIds(actionUser.getDepartmentId(), null, new UidUtil(actionUser.getUid()).toString(),
                    deleteType, isSelf).subscribe(observerActionFromDepartment);
            showWaitDiaLog(deleteSub);
        }
    }
}
